package com.ruoyi.web.controller.topic;

import com.ruoyi.system.domain.User;
import com.ruoyi.system.domain.vo.Result;
import com.ruoyi.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Api(tags = "用户模块")
@RequestMapping("/api")
@RestController
public class UserController extends BaseController {

    @Autowired
    private UserService userService;


    @ApiOperation("查询所有用户")
    @GetMapping("/users")
    public Result<List<User>> listResult(){
        return Result.success(userService.listUser());
    }

    @ApiOperation("根据name查询用户")
    @GetMapping("/users/{loginName}")
    public Result<User> getUserByIdResult(@PathVariable("loginName") String loginName){
        return Result.success(userService.getUserByName(loginName));
    }

    @ApiOperation("添加用户")
    @PostMapping("/users/input")
    public Result<?> addUser(User user, RedirectAttributes attributes){
        User username = userService.getUserByName(user.getNickname());
        if(username!=null){
            attributes.addFlashAttribute("message","fail");
            return Result.fail("已存在该用户");
        }
        int u = userService.saveUser(user);
        if(u == 0){
            attributes.addFlashAttribute("message","success");
        }else {
            attributes.addFlashAttribute("message","fail");
        }
        return Result.success();
    }

    @ApiOperation("修改用户")
    @PostMapping("/users/{userid}")
    public Result<?> updateUser(@PathVariable("userid") Long userid,User user,RedirectAttributes  attributes){
        User username = userService.getUserByName(user.getNickname());
        if(username!=null){
            return Result.fail("已存在该用户");
        }
        int u = userService.updateUser(user);
        if(u == 0){
            attributes.addFlashAttribute("message","success");
        }else {
            attributes.addFlashAttribute("message","fail");
        }
        return Result.success();
    }


    @ApiOperation("删除用户")
    @PostMapping("/delete/{userid}")
    public Result<?> deleteUser(@PathVariable("userid") Long userid){
        userService.deleteUser(userid);
        return Result.success();
    }

}
